package cn.com.czpb.client.module.subscribe;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MyActivitymanager;
import cn.com.czpb.client.config.CODE;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.model.event.PraiseEvent;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsFlashEntity;
import cn.com.czpb.client.model.subscribe.MySubscribeEntity;
import cn.com.czpb.client.module.MainActivity;
import cn.com.czpb.client.module.news.NewsBaseFragment;
import cn.com.czpb.client.module.news.ZixunFragment;
import cn.com.czpb.client.module.news.view.SubscribeTopView;
import cn.com.czpb.client.module.news.view.TopViewPagerView;
import cn.com.czpb.client.module.subscribe.adapter.SubscribeMyAdapterNew;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/20.
 */

public class SubscribeFragment extends NewsBaseFragment implements OnRefreshListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.recycler_list_id)
    RecyclerView recyclerListId;
    @BindView(R.id.swipe_id)
    SmartRefreshLayout swipeId;
    Unbinder unbinder;
    private SubscribeMyAdapterNew adapter;
    private int topnum = 0;
    private int position = -1;
    private int page = 1;
    private static final int pageSize = 15;//
    // 是否刷新最新数据
    private boolean mFlagRefresh;
    private boolean isRefresh = false;//是否首次加载
    private LoginQuitBR br;
    private SubscribeTopView topView;

    private List<NewsBean> strList;
    public static SubscribeFragment newInstance() {
        SubscribeFragment darenhaoFragment = new SubscribeFragment();
        return darenhaoFragment;
    }

    @Override
    public int setMyContentView() {
        return R.layout.fragment_daren_main;
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        br = new LoginQuitBR();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MainActivity.SHOW);
        filter.addAction(MainActivity.UNSHOW);
        activity.registerReceiver(br, filter);
    }
    @Override
    public void initView() {
        topnum = 0;
        //初始化swip
        swipeId.setOnRefreshListener(this);
        swipeId.setRefreshHeader(new ClassHeader_other( activity));
        final LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerListId.setLayoutManager(layoutManager);
        initAdapter();
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        recyclerListId.addOnScrollListener(new RecyclerView.OnScrollListener(){
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //设置什么布局管理器,就获取什么的布局管理器
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                // 当停止滑动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition ,角标值
                    //获取 第一个条目
                    int firstItem = manager.findFirstCompletelyVisibleItemPosition();
                    if (firstItem ==0){
                        ((ZixunFragment)SubscribeFragment.this.getParentFragment()).toVisbility();
                    }
                    //所有条目,数量值
                }
            }
        });
    }
    @Override
    public List<NewsBean> getNewsContent(){
        return strList;
    }
    /**
     * adapter init
     */
    private void initAdapter() {
        topViewPagerView = TopViewPagerView.Instance(activity);
        adapter = new SubscribeMyAdapterNew(null,false,spu.getShowImage());
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this, recyclerListId);
//        SubscribeEmptyView emptyView = SubscribeEmptyView.instance(activity);
//        adapter.setEmptyView(emptyView.getView());
        recyclerListId.setAdapter(adapter);
        topView = SubscribeTopView.instance(activity);
        adapter.addHeaderView(topView.getView(),1);
    }

    @Override
    public void initData() {
        strList = new ArrayList<NewsBean>();
        //首次进入 延迟刷新
        swipeId.postDelayed(new Runnable() {
            @Override
            public void run() {
                mFlagRefresh = true;
                getServerList();
                getFlash();
            }
        }, 200);
    }

    /**
     * 下拉刷新
     */


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        NewsBean itemBean = (NewsBean) adapter.getItem(position);
        switch (view.getId()) {
            case R.id.newsItem_root:
                MyActivitymanager.pushActivity(activity, itemBean, itemBean.getTid(), "newsitem",itemBean.getRvalue());
                break;
            //TODO
        }
    }

    @Subscribe
    public void onEventMainThread(PraiseEvent event) {
        String nid = event.getNid();
        String praisenum = event.getPraisecount();
        LogUtils.e("event.getNid:"+nid+"event.getPraisecount:"+praisenum);
        LogUtils.e("topnum:"+topnum);
        LogUtils.e("adapter.getData.size:"+adapter.getData().size());
        for(int i=0;i<adapter.getData().size();i++){
            if(adapter.getData().get(i).getNid().equals(nid)){
                adapter.getData().get(i).setPraisecount(praisenum);
                adapter.notifyItemChanged(i+topnum);
                LogUtils.e("notifyitem:"+(i+topnum));
            }
        }
    }
    private int mCurrentCounter = 0;
    private static final int TOTAL_COUNTER = 18;
    private boolean isErr;
    private boolean mLoadMoreEndGone = false;

    @Override
    public void onLoadMoreRequested() {
        mFlagRefresh = false;
        page++;
        showDialog_index();
        getServerList();
    }
    /**
     * 我订阅的达人号发表的纹章
     */
    public void getServerList() {
        LogUtils.i("init", "getNewslist");
        Map<String, String> map = new HashMap<>();
//        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("Page", page + "");
        map.put("PageSize", pageSize + "");
        map.put("device", DeviceUtils.getMyUUID(activity));
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
            LogUtils.i("uid-->" + spu.getUser().getUid());
        }
        Factory.provideHttpService()
                .mySubscribeList(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<MySubscribeEntity, Boolean>() {
                    @Override
                    public Boolean call(MySubscribeEntity entity) {

                        if ("200".equals(entity.code)) {
                            LogUtils.i("200--list>成功");
                            return true;
                        }
                        LogUtils.i("list>失败" + entity.code);
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<MySubscribeEntity>() {
                    @Override
                    public void call(MySubscribeEntity entity) {
                        disMissDialog_index();
                        if (mFlagRefresh) {
                            swipeId.finishRefresh();
                        }
                        swipeId.finishRefresh();
                        if ("200".equals(entity.code)) {
                            if ("0".equals(entity.data.getLogin())){
                                topView.setVisibile(true);
                            }else{
                                topView.setVisibile(false);
                            }
                            setListData(entity.data.getList());
                            if (mFlagRefresh) {
                            }

                        } else {

                            if (mFlagRefresh) {
                                swipeId.finishRefresh();
                            }

//                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        swipeId.finishRefresh();
                        adapter.setNewData(null);
                        if (mFlagRefresh) {
                        }
                        LogUtils.i("异常-->" + throwable.toString());
                        adapter.loadMoreFail();
                    }
                });


    }

    public void setListData(List<NewsBean> list) {
        if (mFlagRefresh) {
            strList.clear();
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        for (NewsBean bean :list
                ) {
            strList.add(bean);
        }
        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < pageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }
    private Boolean isFirstLoadFlash = true;
    private TopViewPagerView topViewPagerView;
    //    获取幻灯
    private void getFlash() {
        LogUtils.i("init", "getflash");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", CODE.TID_SUBSCRIPT);
        Factory.provideHttpService()
                .newsFlashlist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsFlashEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsFlashEntity entity) {
                        LogUtils.i("flash--200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsFlashEntity>() {
                               @Override
                               public void call(NewsFlashEntity entity) {
                                       if (isFirstLoadFlash) {
                                           LogUtils.i("flash--200-->成功-first");

                                           isFirstLoadFlash = false;

                                           isFirstLoadFlash = false;
                                           adapter.addHeaderView(topViewPagerView.getView(),0);
                                           topnum++;
                                           topViewPagerView.reFreshFlashData(entity.data.flash);
                                       } else {
                                           topViewPagerView.reFreshFlashData(entity.data.flash);
                                       }
                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {

                                   LogUtils.i("flash--200-->失败" + throwable.toString());
                               }
                           }
                );
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isFirstLoadFlash = true;
        unbinder.unbind();
    }

//    @OnClick({R.id.ll_subscribe_me, R.id.ll_subscribe_more})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.ll_subscribe_me:
//                PageCtrl.start2SubscribeMeActivity(activity);
//                break;
//            case R.id.ll_subscribe_more:
//                PageCtrl.start2SubscribeMoreActivity(activity);
//                break;
//        }
//    }


    public class LoginQuitBR extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(MainActivity.SHOW)) {
                adapter.notifyDataSetChanged();
            } else if (action.equals(MainActivity.UNSHOW)) {
                adapter.notifyDataSetChanged();
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        activity.unregisterReceiver(br);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                mFlagRefresh = true;
                getServerList();

            }
        },2000);
    }
    private String mTitle;
    public void setTitle(String title) {
        mTitle = title;
    }

    public String getTitle() {
        return mTitle;
    }

    @Override
    public void init() {

    }
}
